from flask_restful import Resource
from flask import g
from app.auth.models import UserAuth
from app.common.constants import ResultCode
from app.common.response import api_response
from app import user_app


class Register(Resource):
    """ 注册 类试图 """
    user_auth = UserAuth()

    def post(self):
        data = g.data
        result = self.user_auth.register(data)
        if result:
            response = api_response(result_code=ResultCode.REGISTER, user_id=data['user_id'])
            user_app.logger.error({"message": 'register - data:{} success'.format(data)})
        else:
            response = api_response(result_code=ResultCode.REGISTERED, user_id=data['user_id'])
            user_app.logger.error({"message": 'register - data:{} existed'.format(data)})
        return response


class Login(Resource):
    """ 登录 类试图 """
    user_auth = UserAuth()

    def post(self):
        data = g.data
        result = self.user_auth.login(data)
        if result:
            response = api_response(result_code=result['response'], tokens=result['token'], user_id=data['user_id'])
            if result['token']:
                user_app.logger.error({"message": 'login - data:{} success'.format(data)})
            else:
                user_app.logger.error({"message": 'login - data:{} pwd-mistake'.format(data)})
        else:
            response = api_response(result_code=ResultCode.NON_EXISTENT)
            user_app.logger.error({"message": 'login - data:{} does not exist'.format(data)})
        return response




